# -*- coding: utf-8 -*-
import ctypes
import sys
import time
import traceback
from tkinter import *
from tkinter import messagebox
from src.conf.conf import getConf
from src.jianghu.main import Main


publicData = getConf(n=0)

# def get_api_time():
#     for i in range(3):
#
#         try:
#             url="https://timeapi.io/api/Time/current/zone?timeZone=UTC"
#             myURL = urllib.request.urlopen(url)
#
#             content = myURL.read()  # 读取网页内容
#
#             response = requests.get('')
#
#             x=response.raise_for_status()
#
#             time_data = response.json()
#             print("API network time: ", time_data['dateTime'])
#
#         except requests.exceptions.RequestException as e:
#
#             continue
#
# get_api_time()

def UI():
    # 创建主窗口
    top = Tk()
    top.title("江湖出装模拟器[%s]"%publicData["系统"]["沙盒名称"])  # 标题设置
    top.geometry('600x150')
    # 调用主事件循环，让窗口程序保持运行。
    objList= {}
    main = Main(1, "main", 1, getConf(0), True)
    ButtonCanClick={
        "start":True,
        "goOn":False,
        "pause":False,
        "stop":False,
    }

    def show_bubble(root, text, x, y):
        bubble = Label(root, text=text, bg='lightyellow', relief='solid', borderwidth=1)
        bubble.place(x=x, y=y)
        root.after(5000, bubble.destroy)  # 2秒后自动消失

    def start():
        if ButtonCanClick["start"]:
            # messagebox.showinfo("信息", "这是一个信息弹窗")
            objList["main"]=main
            main.start()
            main.HandleFlag("RUNNING")
            ButtonCanClick["start"]=False
            ButtonCanClick["goOn"] =False
            ButtonCanClick["pause"] = True
            ButtonCanClick["stop"] = True
        time.sleep(1)
    def startEvent(event):
        show_bubble(top, "启动中！", 260, 0)
        start()
    def goOn():
        if ButtonCanClick["goOn"]:
            objList["main"]=main
            main.HandleFlag("RUNNING")
            ButtonCanClick["goOn"] = False
            ButtonCanClick["pause"] = True

    def goOnEvent(event):
        show_bubble(top, "恢复中！", 260, 0)
        goOn()

    def pause():
        if ButtonCanClick["pause"]:
            try:
                objList["main"].HandleFlag("PAUSE")
            except AttributeError:
                print("请启动后再暂停")
            ButtonCanClick["goOn"] = True
            ButtonCanClick["pause"] = False
    def pauseEvent(event):
        show_bubble(top, "暂停中！", 260, 0)
        pause()
    def stop():
        if ButtonCanClick["stop"]:
            try:
                objList["main"].HandleFlag("STOP")
            except AttributeError:
                print("请启动后再停止")
            ButtonCanClick["start"] = True
            ButtonCanClick["goOn"] = False
            ButtonCanClick["pause"] = True
            ButtonCanClick["stop"] = True
    def stopEvent(event):
        show_bubble(top, "结束中！", 300, 0)
        stop()
    textData=Label(top, text="", fg="black")
    textData.pack()
    Button(top, text="启动<f9>", fg="black", command=start).pack()
    Button(top, text="继续<f10>", fg="black", command=goOn).pack()
    Button(top, text="暂停<f11>（尽量在游戏中使用，不要手动进行关键操作如选门派，拿武器 合成洗髓经等）", fg="black", command=pause).pack()
    Button(top, text="停止<f12>（多开时,点击此按钮并等待弹起再等待3s，再关闭窗口）", fg="black", command=stop).pack()
    text="如果暂停后3s+,\n仍出现占用鼠标的情况，\n请使用快捷键结束"
    bubble = Label(top, text=text, bg='lightyellow', relief='solid', borderwidth=1)
    bubble.config(width=25,height=3)
    bubble.place(x=350, y=10)

    top.bind("<F9>",func=startEvent)
    top.bind("<F10>", func=goOnEvent)
    top.bind("<F11>", func=pauseEvent)
    top.bind("<F12>", func=stopEvent)
    textData.config(text="")
    top.mainloop()



CODE=0xC0000005


def handle_seh_exception(code):
    print("err found")
    time.sleep(10)
    if code==CODE:
        print(CODE)
    else:
        print(code)
    return 1


def set_seh_handle():
    if sys.platform!="win32":
        return
    # 期望返回dll 异常退出  好像没用
    kernel32 =ctypes.WinDLL("kernel32",use_last_error=True)
    setUbhandleExceptionFilter = kernel32.SetUnhandledExceptionFilter
    setUbhandleExceptionFilter.argtypes = [ctypes.WINFUNCTYPE(ctypes.c_int,ctypes.POINTER(ctypes.c_ulong))]
    def seh_filter(info):
        code =ctypes.c_ulong(0)
        ctypes.memmove(ctypes.byref(code),info.contents.ExceptionRecord.contents.ExceptionCode,ctypes.sizeof(ctypes.c_ulong))
        handle_seh_exception(info.value)
        return 1
    setUbhandleExceptionFilter(ctypes.WINFUNCTYPE(ctypes.c_int,ctypes.POINTER(ctypes.c_ulong))(seh_filter))



if __name__ == '__main__':
    set_seh_handle()
    try:
        print("起动UI")
        UI()
        time.sleep(3)
        print("运行结束")
    except EXCEPTION as e:
        print(e)
        print("---------------")
        traceback.print_exc()







